﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.IO;
using System.Data.SqlServerCe;
using System.Data.SqlClient;

namespace ERPForms
{
    public partial class RestoreUnitatiFrm : StudioForm
    {
        private String numeBaza = String.Empty;

        public RestoreUnitatiFrm(ModuleClass mc): base(mc)
        {
            InitializeComponent();
            tableAdapterManager.UnitatiTableAdapter.Adapter.RowUpdated += Adapter_RowUpdatedUnitati;
            tableAdapterManager.arhRulajeDocTableAdapter.Adapter.RowUpdated += Adapter_RowUpdatedarhRulajeDoc;
            tableAdapterManager.ParteneriTableAdapter.Adapter.RowUpdated +=Adapter_RowUpdatedParteneri;
            tableAdapterManager.ArticoleTableAdapter.Adapter.RowUpdated +=Adapter_RowUpdatedArticole;
            tableAdapterManager.DocumenteTableAdapter.Adapter.RowUpdated +=Adapter_RowUpdatedDocumente;
            tableAdapterManager.RulajeDocTableAdapter.Adapter.RowUpdated+=Adapter_RowUpdatedRulajeDoc;
            tableAdapterManager.DocumentePlataTableAdapter.Adapter.RowUpdated +=Adapter_RowUpdatedDocumentePlata;
        }

        private void SetImportStatus()
        {
            int cate = 0;
            foreach (DataTable dt in exportESRPDataSet.Tables)
            {
                cate += dt.Select(String.Empty, String.Empty, DataViewRowState.Added).Length;
            }
            SetProgressBar(totalRowAdded-cate);        
        }

        void Adapter_RowUpdatedUnitati(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.Errors != null)
                throw e.Errors;

            SetImportStatus();
            if (e.StatementType == StatementType.Insert)
            {
                foreach (DataTable dt in exportESRPDataSet.Tables)
                {
                    if (dt.Columns.Contains("CodUnitate"))
                    {
                        foreach (DataRow row in dt.Select("CodUnitate=" + e.Row["CodUnitate", DataRowVersion.Original].ToString(),
                                "CodUnitate", DataViewRowState.Added))
                        {
                            row["CodUnitate"] = e.Row["CodUnitate"];
                        }
                    }
                }
            }
        }

        void Adapter_RowUpdatedarhRulajeDoc(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.Errors != null)
                throw e.Errors;
            SetImportStatus();
            if (e.StatementType == StatementType.Insert)
            {
                foreach (DataRow row in exportESRPDataSet.arhRulaje.Select("IDDocument=" + e.Row["IDDocument", DataRowVersion.Original].ToString(),
                        "IDDocument", DataViewRowState.Added))
                {
                    row["IDDocument"] = e.Row["IDDocument"];
                }
            }
        }

        void Adapter_RowUpdatedParteneri(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.Errors != null)
                throw e.Errors;
            SetImportStatus();
            if (e.StatementType == StatementType.Insert)
            {
                foreach (DataTable dt in exportESRPDataSet.Tables)
                {
                    if (dt.Columns.Contains("IDPartener"))
                    {
                        foreach (DataRow row in dt.Select("IDPartener=" + e.Row["IDPartener", DataRowVersion.Original].ToString(),
                                "IDPartener", DataViewRowState.Added))
                        {
                            row["IDPartener"] = e.Row["IDPartener"];
                        }
                    }
                }
            }
        }

        void Adapter_RowUpdatedArticole(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.Errors != null)
                throw e.Errors;
            SetImportStatus();
            if (e.StatementType == StatementType.Insert)
            {
                foreach (DataTable dt in exportESRPDataSet.Tables)
                {
                    if (dt.Columns.Contains("IDArticol"))
                    {
                        foreach (DataRow row in dt.Select("IDArticol=" + e.Row["IDArticol", DataRowVersion.Original].ToString(),
                                "IDArticol", DataViewRowState.Added))
                        {
                            row["IDArticol"] = e.Row["IDArticol"];
                        }
                    }
                }
            }
        }

        void Adapter_RowUpdatedDocumente(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.Errors != null)
                throw e.Errors;
            SetImportStatus();
            if (e.StatementType == StatementType.Insert)
            {
                foreach (DataRow row in exportESRPDataSet.DocumenteDetaliu.Select("IDDocument=" + e.Row["IDDocument", DataRowVersion.Original].ToString(),
                        "IDDocument", DataViewRowState.Added))
                {
                    row["IDDocument"] = e.Row["IDDocument"];
                }
                foreach (DataRow row in exportESRPDataSet.DocumentePlataDetaliu.Select("IDDocument=" + e.Row["IDDocument", DataRowVersion.Original].ToString(),
                        "IDDocument", DataViewRowState.Added))
                {
                    row["IDDocument"] = e.Row["IDDocument"];
                }
            }

        }

        void Adapter_RowUpdatedRulajeDoc(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.Errors != null)
                throw e.Errors;
            SetImportStatus();
            if (e.StatementType == StatementType.Insert)
            {
                foreach (DataRow row in exportESRPDataSet.Rulaje.Select("IDDocument=" + e.Row["IDDocument", DataRowVersion.Original].ToString(),
                        "IDDocument", DataViewRowState.Added))
                {
                    row["IDDocument"] = e.Row["IDDocument"];
                }
                
            }

        }

        void Adapter_RowUpdatedDocumentePlata(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.Errors != null)
                throw e.Errors;
            if (e.StatementType == StatementType.Insert)
            {
                foreach (DataRow row in exportESRPDataSet.DocumentePlataDetaliu.Select("IDDocumentPlata=" + e.Row["IDDocumentPlata", DataRowVersion.Original].ToString(),
                        "IDDocumentPlata", DataViewRowState.Added))
                {
                    row["IDDocumentPlata"] = e.Row["IDDocumentPlata"];
                }

            }

        }

        private void RestoreUnitatiFrm_Load(object sender, EventArgs eargs)
        {
     
            AddButton("Restore", global::ERPStudio.Properties.Resources._001_08, Restore, ToolStripItemAlignment.Right, true);
            string catCurent = Directory.GetCurrentDirectory();
            string catModule = catCurent + @"\Backup";
            DirectoryInfo catInfo = new DirectoryInfo(catModule);
            try
            {
                var txtFiles = Directory.GetFiles(catModule, "*.sdf");

                foreach (string currentFile in txtFiles)
                {
                    //string fileName = currentFile.Substring(sourceDirectory.Length + 1);
                    BackupCBL.Items.Add(currentFile.Replace(catModule+"\\",String.Empty));
                }
            }
            catch (Exception e)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare restore", e.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, this);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                return;
            }


        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs eargs)
        {
            if (BackupCBL.CheckedItems.Count ==0 && tabControl1.SelectedIndex==1)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Selectie backup","Va rugam selectati un backup inainte de a selectata unitatea care se va restaura!", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, this);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                tabControl1.SelectedIndex = 0;
                return;
            }
            if (BackupCBL.CheckedItems.Count > 1 && tabControl1.SelectedIndex == 1)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Selectie backup", "Va rugam selectati doar un  singur backup!", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, this);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                tabControl1.SelectedIndex = 0;
                return;
            }

            if (tabControl1.SelectedIndex == 1)
            {
                string catCurent = Directory.GetCurrentDirectory();
                string catModule = catCurent + @"\Backup";
                String cale = BackupCBL.Items[BackupCBL.SelectedIndex].ToString();
                ListaUnitatiCBL.Items.Clear();
                numeBaza = "Data Source=" + catModule + "\\" + cale;
                using (SqlCeConnection conn = new SqlCeConnection(numeBaza))
                
                {
                    String comanda = String.Empty;
                    try
                    {
                        conn.Open();
                        SqlCeCommand ceCmd = new SqlCeCommand("SELECT * FROM [Unitati] WHERE [CodUnitate]<>0", conn);
                        SqlCeDataReader drUnitati = ceCmd.ExecuteReader();
                        while (drUnitati.Read())
                        {
                            String nume_unitate = drUnitati.GetValue(drUnitati.GetOrdinal("Denumire")).ToString();
                            int idxAdd = ListaUnitatiCBL.Items.Add(new CheckListBoxItem()
                                {
                                    Tag = drUnitati.GetValue(drUnitati.GetOrdinal("CodUnitate")),
                                    Text = nume_unitate
                                });
                                
                        }

                        drUnitati.Close();
                        conn.Close();
                    }
                    catch (Exception e)
                    {
                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare restore", e.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, this);
                        mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.ShowDialog();
                        return;
                    }

                }
            }
        }

        private void Restore(object sender, EventArgs eargs)
        {
            if (ListaUnitatiCBL.CheckedItems.Count == 0)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Selectie unitate restore", "Va rugam selectati unitatea care se va restaura!", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, this);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                tabControl1.SelectedIndex = 1;
                return;
            }

            MessageBoxFrm mbti = new MessageBoxFrm("atentie", "Datele existente in acest moment se vor suprascrie cu cele din backup!", "Sunteti sigur ca doriti acest lucru?", MessageBoxFrm.ImaginiMB.StopIcon, this);
            mbti.AddButton("Da", 70, mbti.MessageBoxFrm_Click_Yes);
            mbti.AddButton("Nu", 70, mbti.MessageBoxFrm_Click_No);
            if (mbti.ShowDialog() == System.Windows.Forms.DialogResult.No)
                return;

            Boolean err = false;
            List<Int32> CodUList = new List<Int32>();
            foreach (object itm in ListaUnitatiCBL.CheckedItems)
            {
                CheckListBoxItem itmTag = itm as CheckListBoxItem;
                CodUList.Add(Convert.ToInt32(itmTag.Tag));
            }

            if (!RestoreUnitate(CodUList))
                err = true;


            if (!err)
            {
                MessageBoxFrm mbt2 = new MessageBoxFrm("Restaurare", "Unitatile au fost restaurate cu succes!", String.Empty, MessageBoxFrm.ImaginiMB.InformareIcon, this);
                mbt2.AddButton("Ieşire", 70, mbt2.MessageBoxFrm_Click_Yes);
                mbt2.ShowDialog();
            }
            else
            {
                MessageBoxFrm mbt3 = new MessageBoxFrm("Restaurare", "Unitatile nu au fost restaurate!", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, this);
                mbt3.AddButton("Ieşire", 70, mbt3.MessageBoxFrm_Click_Yes);
                mbt3.ShowDialog();            
            }
        
        }


        int totalRowAdded = 0;
        private Boolean RestoreUnitate(List<Int32> CodUnitate)
        {
            Cursor.Current = Cursors.WaitCursor;
            SqlConnection con = DeschideConexiune(workConnString);
            SqlCommand cmd = new SqlCommand("", con);
            cmd.Transaction = con.BeginTransaction();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "StergeUnitate";
            String unitatiSelectate = String.Empty;
            foreach (Int32 cu in CodUnitate)
            {
                cmd.Parameters.Clear();
                cmd.Parameters.Add(new SqlParameter("CodUnitate", cu));//@faraStergereTabelaUnitati
                unitatiSelectate += cu.ToString() + ",";
                cmd.Parameters.Add(new SqlParameter("faraStergereTabelaUnitati", false));
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare restore", e.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, this);
                    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    cmd.Transaction.Rollback();
                    InchideConexiune(con);
                    Cursor.Current = Cursors.Default;
                    return false;
                }
            }
            unitatiSelectate = unitatiSelectate.TrimEnd(new char[] { ',', '\n' });
            cmd.Transaction.Commit();

            String comanda = String.Empty;
            using (SqlCeConnection conn = new SqlCeConnection(numeBaza))
            {
                conn.Open();
                foreach (DataTable dt in exportESRPDataSet.Tables)
                {
                    try
                    {
                        SqlCeCommand ceCmd = new SqlCeCommand("SELECT * FROM ["+dt.TableName+"]" , conn);
                        SqlCeDataReader drUnitati = ceCmd.ExecuteReader();
                        dt.Load(drUnitati, LoadOption.OverwriteChanges);
                        foreach (DataRow dr in dt.Rows)
                        {
                            dr.SetAdded();
                            //trim la campurile de tip caracter
                            foreach (DataColumn dc in dt.Columns)
                            {
                                if (dc.DataType == typeof(String) && !dc.ReadOnly && dr[dc]!=DBNull.Value)
                                    dr[dc] = dr[dc].ToString().Trim();
                            }
                        }
                        drUnitati.Close();
                    }
                    catch (Exception e)
                    {
                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare restore", e.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, this);
                        mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.ShowDialog();
                        Cursor.Current = Cursors.Default;
                        return false;
                    }
                }
                conn.Close();
            }

            
            foreach (DataTable dt in exportESRPDataSet.Tables)
            {
                totalRowAdded += dt.Select(String.Empty, String.Empty, DataViewRowState.Added).Length;
            }
            EnableProgressBar(0, totalRowAdded);        



            tableAdapterManager.Connection = con;
            
            if ((exportESRPDataSet.HasChanges() == false))
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare restore","Nu s-au incarcat tabelele din arhiva", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, this);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                Cursor.Current = Cursors.Default;
                return false;
            }
            try
            {
                cmd.CommandText = "DISABLE trigger VerificaTotalDocument ON DocumentePlataDetaliu";
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();

                tableAdapterManager.UpdateAll(exportESRPDataSet);

                cmd.CommandText = "ENABLE trigger VerificaTotalDocument ON DocumentePlataDetaliu";
                cmd.ExecuteNonQuery();

            }
            catch (Exception e)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare restore", e.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, exportESRPDataSet.Tables);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                Cursor.Current = Cursors.Default;
                DisableProgressBar();
                return false;

            }


            InchideConexiune(con);
            Cursor.Current = Cursors.Default;
            DisableProgressBar();
            return true;
        }

       

    }

    class CheckListBoxItem
    {
        public object Tag;
        public string Text;
        public override string ToString() { return Text; }
    }


}
